package com.hup.timer.view.dialog;

import com.hup.timer.constant.TimerConstant;
import com.hup.timer.model.TimeViewConfig;
import com.hup.timer.model.TimerConfig;
import com.hup.timer.mvp.MainMvp.MainPresenter;
import com.hup.timer.view.TimerWindow;
import com.hup.utils.commons.start.DialogHelper;
import com.hup.utils.commons.start.SpringContext;
import com.hup.utils.swing.customView.colorChooser.ColorChooserPanel;
import com.hup.utils.swing.customView.spinner.IntSpinner;
import com.hup.utils.swing.frame.BaseDialog;
import com.hup.utils.swing.frame.SingletonWindowHelper;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.BeanUtils;

import javax.swing.BorderFactory;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.border.TitledBorder;
import java.awt.Color;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionListener;

@Log4j2
public class AppConfigDialog extends BaseDialog {
    /**
     * 用来处理[用户重复点击打开窗口按钮]的情况;在每次关闭窗口时都会置空
     */
    private JPanel contentPane;
    private JButton btnOK;
    private JButton btnCancel;
    public JButton btnApply;
    public JButton btnDefault;

    public JCheckBox cbClickOnce;
    public JCheckBox cb12H;
    public JCheckBox cbDisableWindowMenu;

    public JCheckBox cbAutoOnTop;
    public IntSpinner txtAutoOnTopSpan;
    public JCheckBox cbEnableOnTopHotKey;

    public JRadioButton rbBgColor;
    public JRadioButton rbFontColor;
    public ColorChooserPanel colorChooser;

    private TimerConfig timerConfig;
    /**
     * 实现[即时预览]效果;配置在初始化时
     */
    private TimeViewConfig previewConfig;
    private TimerWindow timerWindow;

    /**
     * 有无改动过配置
     */
    private boolean hasChange;

    public AppConfigDialog() {
        super("设置");
        setContentPane(contentPane);
        setModal(false);
        getRootPane().setDefaultButton(btnOK);
        btnOK.setEnabled(false);
        btnApply.setEnabled(false);

        initFrameListener();

        MainPresenter mainPresenter = SpringContext.getBean(MainPresenter.class);
        timerConfig = mainPresenter.getConfig();
        previewConfig = new TimeViewConfig(timerConfig);
        initByConfig(timerConfig, previewConfig);

        timerWindow = mainPresenter.getTimerWindow();

        initConfigViewListener();
    }

    private void initFrameListener() {
        btnOK.addActionListener(e -> onOK(true));
        btnApply.addActionListener(e -> onOK(false));
        btnCancel.addActionListener(e -> onCancel());
        btnDefault.addActionListener(confirm("恢复默认", () -> {
            TimerConfig defaultConfig = new TimerConfig();
            previewConfig = defaultConfig.timeViewConfig;//要重新赋值,不然下次修改颜色是会bug
            defaultConfig.timeWindowConfig.afterLoadFromFileOrReset(null);

            initByConfig(defaultConfig, previewConfig);
            timerWindow.applyPreviewConfig(previewConfig);
            timerWindow.setLocation(defaultConfig.timeWindowConfig.getLoc());
            btnApply.setEnabled(true);
        }));
    }

    private void initConfigViewListener() {
        ActionListener lsn = e -> {
            hasChange = true;
            btnOK.setEnabled(true);
            btnApply.setEnabled(true);
            if (e.getSource() == cb12H) {
                previewConfig.is12H = cb12H.isSelected();
                timerWindow.applyPreviewConfig(previewConfig);
            }
        };
        cbAutoOnTop.addActionListener(lsn);
        cb12H.addActionListener(lsn);
        cbDisableWindowMenu.addActionListener(lsn);

        cbClickOnce.addActionListener(lsn);
        cbEnableOnTopHotKey.addActionListener(lsn);

        txtAutoOnTopSpan.addChangeListener(e -> {
            hasChange = true;
            cbAutoOnTop.setSelected(true);
            btnOK.setEnabled(true);
            btnApply.setEnabled(true);
        });

        rbFontColor.addActionListener(e -> colorChooser.updateTo(previewConfig.getFontColor()));
        rbBgColor.addActionListener(e -> colorChooser.updateTo(previewConfig.getPreviewBgColor()));
        colorChooser.setColorInvoker((source, color) -> {
            if (color.getAlpha() < TimerConstant.ALPHA_MIN * 255f) {
                //限制最低透明度
                color = new Color(color.getRed(), color.getGreen(), color.getBlue(), (int) (TimerConstant.ALPHA_MIN * 255));
                colorChooser.revertTo(color);
            }
            hasChange = true;
            btnOK.setEnabled(true);
            btnApply.setEnabled(true);
            if (rbFontColor.isSelected()) {
                previewConfig.setFontColorI(color.getRGB());
            } else {
                previewConfig.setBgColorI(color.getRGB());
            }
            timerWindow.applyPreviewConfig(previewConfig);
        });
    }

    private void initByConfig(TimerConfig timerConfig, TimeViewConfig previewConfig) {
        cbAutoOnTop.setSelected(timerConfig.autoOnTop);
        cb12H.setSelected(previewConfig.is12H);
        cbDisableWindowMenu.setSelected(timerConfig.timeWindowConfig.disableWindowMenu);

        txtAutoOnTopSpan.setValue(timerConfig.autoOnTopSpan);
        cbClickOnce.setSelected(!timerConfig.actBy2Click);
        cbEnableOnTopHotKey.setSelected(timerConfig.enableOnTopGlobalHotKey);

        //form中默认选中[字体色],但[恢复默认]时也会调用此方法
        if (rbFontColor.isSelected()) {
            colorChooser.updateTo(previewConfig.getFontColor());
        } else {
            colorChooser.updateTo(previewConfig.getPreviewBgColor());
        }
    }

    private void onOK(boolean dispose) {
        log.info("");
        if (hasChange) {
            timerConfig.actBy2Click = !cbClickOnce.isSelected();
            //timerConfig.timeViewConfig.is12H//会由previewConfig覆盖
            timerConfig.timeWindowConfig.disableWindowMenu = cbDisableWindowMenu.isSelected();

            timerConfig.autoOnTop = cbAutoOnTop.isSelected();
            timerConfig.autoOnTopSpan = (Integer) txtAutoOnTopSpan.getValue();
            timerConfig.enableOnTopGlobalHotKey = cbEnableOnTopHotKey.isSelected();
            BeanUtils.copyProperties(previewConfig, timerConfig.timeViewConfig);
            timerConfig.timeWindowConfig.loc = timerWindow.getLocation();

            timerConfig.save();
            timerConfig.fireConfigChanged();
        }

        hasChange = false;
        if (dispose) {
            dispose();
        } else {
            btnApply.setEnabled(false);
        }
    }

    @Override
    public void onCancel() {
        if (!hasChange) {
            dispose();
        } else {
            DialogHelper.yesNo("是否放弃保存配置?").okAction(() -> {
                //还原配置
                timerWindow.applyPreviewConfig(timerConfig.timeViewConfig);
                dispose();
            }).show();
        }
    }

    public static void doShow() {
        AppConfigDialog dialog = SingletonWindowHelper.getWindow(AppConfigDialog.class);
        if (dialog == null) {
            dialog = new AppConfigDialog();
            dialog.pack();
            dialog.setLocationRelativeTo(null);
        }
        dialog.setVisible(true);
    }

    {
// GUI initializer generated by IntelliJ IDEA GUI Designer
// >>> IMPORTANT!! <<<
// DO NOT EDIT OR ADD ANY CODE HERE!
        $$$setupUI$$$();
    }

    /**
     * Method generated by IntelliJ IDEA GUI Designer
     * >>> IMPORTANT!! <<<
     * DO NOT edit this method OR call it in your code!
     *
     * @noinspection ALL
     */
    private void $$$setupUI$$$() {
        contentPane = new JPanel();
        contentPane.setLayout(new GridBagLayout());
        contentPane.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10), null, TitledBorder.DEFAULT_JUSTIFICATION, TitledBorder.DEFAULT_POSITION, null, null));
        final JPanel panel1 = new JPanel();
        panel1.setLayout(new GridBagLayout());
        GridBagConstraints gbc;
        gbc = new GridBagConstraints();
        gbc.gridx = 0;
        gbc.gridy = 1;
        gbc.weightx = 1.0;
        gbc.fill = GridBagConstraints.BOTH;
        contentPane.add(panel1, gbc);
        final JPanel panel2 = new JPanel();
        panel2.setLayout(new GridBagLayout());
        gbc = new GridBagConstraints();
        gbc.gridx = 1;
        gbc.gridy = 0;
        gbc.fill = GridBagConstraints.BOTH;
        panel1.add(panel2, gbc);
        btnOK = new JButton();
        btnOK.setText("确定");
        gbc = new GridBagConstraints();
        gbc.gridx = 0;
        gbc.gridy = 0;
        gbc.fill = GridBagConstraints.HORIZONTAL;
        panel2.add(btnOK, gbc);
        btnCancel = new JButton();
        btnCancel.setText("取消");
        gbc = new GridBagConstraints();
        gbc.gridx = 1;
        gbc.gridy = 0;
        gbc.fill = GridBagConstraints.HORIZONTAL;
        panel2.add(btnCancel, gbc);
        btnDefault = new JButton();
        btnDefault.setText("恢复默认");
        gbc = new GridBagConstraints();
        gbc.gridx = 3;
        gbc.gridy = 0;
        gbc.fill = GridBagConstraints.HORIZONTAL;
        panel2.add(btnDefault, gbc);
        btnApply = new JButton();
        btnApply.setText("应用");
        gbc = new GridBagConstraints();
        gbc.gridx = 2;
        gbc.gridy = 0;
        gbc.fill = GridBagConstraints.HORIZONTAL;
        panel2.add(btnApply, gbc);
        final JPanel spacer1 = new JPanel();
        gbc = new GridBagConstraints();
        gbc.gridx = 0;
        gbc.gridy = 0;
        gbc.weightx = 1.0;
        gbc.fill = GridBagConstraints.HORIZONTAL;
        panel1.add(spacer1, gbc);
        final JPanel panel3 = new JPanel();
        panel3.setLayout(new GridBagLayout());
        gbc = new GridBagConstraints();
        gbc.gridx = 0;
        gbc.gridy = 0;
        gbc.weightx = 1.0;
        gbc.weighty = 1.0;
        gbc.fill = GridBagConstraints.BOTH;
        contentPane.add(panel3, gbc);
        final JPanel panel4 = new JPanel();
        panel4.setLayout(new GridBagLayout());
        gbc = new GridBagConstraints();
        gbc.gridx = 0;
        gbc.gridy = 0;
        gbc.fill = GridBagConstraints.BOTH;
        panel3.add(panel4, gbc);
        panel4.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(), "一般设置", TitledBorder.DEFAULT_JUSTIFICATION, TitledBorder.DEFAULT_POSITION, null, null));
        final JPanel panel5 = new JPanel();
        panel5.setLayout(new GridBagLayout());
        gbc = new GridBagConstraints();
        gbc.gridx = 0;
        gbc.gridy = 0;
        gbc.weightx = 1.0;
        gbc.anchor = GridBagConstraints.WEST;
        gbc.fill = GridBagConstraints.VERTICAL;
        panel4.add(panel5, gbc);
        cbClickOnce = new JCheckBox();
        cbClickOnce.setHorizontalTextPosition(2);
        cbClickOnce.setText("单击操作");
        cbClickOnce.setToolTipText("使用单击或双击激活鼠标操作");
        gbc = new GridBagConstraints();
        gbc.gridx = 1;
        gbc.gridy = 0;
        gbc.fill = GridBagConstraints.HORIZONTAL;
        panel5.add(cbClickOnce, gbc);
        cb12H = new JCheckBox();
        cb12H.setHorizontalTextPosition(2);
        cb12H.setText("12小时制");
        gbc = new GridBagConstraints();
        gbc.gridx = 0;
        gbc.gridy = 0;
        gbc.anchor = GridBagConstraints.WEST;
        panel5.add(cb12H, gbc);
        cbDisableWindowMenu = new JCheckBox();
        cbDisableWindowMenu.setHorizontalTextPosition(2);
        cbDisableWindowMenu.setText("禁用窗口菜单");
        cbDisableWindowMenu.setToolTipText("避免影响全屏中的游戏");
        gbc = new GridBagConstraints();
        gbc.gridx = 0;
        gbc.gridy = 1;
        gbc.anchor = GridBagConstraints.WEST;
        panel5.add(cbDisableWindowMenu, gbc);
        final JPanel panel6 = new JPanel();
        panel6.setLayout(new GridBagLayout());
        gbc = new GridBagConstraints();
        gbc.gridx = 0;
        gbc.gridy = 1;
        gbc.fill = GridBagConstraints.BOTH;
        panel3.add(panel6, gbc);
        panel6.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(), "窗口置顶", TitledBorder.DEFAULT_JUSTIFICATION, TitledBorder.DEFAULT_POSITION, null, null));
        cbAutoOnTop = new JCheckBox();
        cbAutoOnTop.setHorizontalTextPosition(2);
        cbAutoOnTop.setText("定时置顶");
        cbAutoOnTop.setToolTipText("定时解决窗口被其他界面覆盖的问题");
        gbc = new GridBagConstraints();
        gbc.gridx = 0;
        gbc.gridy = 0;
        gbc.fill = GridBagConstraints.HORIZONTAL;
        panel6.add(cbAutoOnTop, gbc);
        final JLabel label1 = new JLabel();
        label1.setText("置顶间隔(秒)");
        gbc = new GridBagConstraints();
        gbc.gridx = 1;
        gbc.gridy = 0;
        gbc.anchor = GridBagConstraints.WEST;
        gbc.insets = new Insets(0, 30, 0, 0);
        panel6.add(label1, gbc);
        txtAutoOnTopSpan = new IntSpinner();
        txtAutoOnTopSpan.setMax(59);
        txtAutoOnTopSpan.setMin(0);
        gbc = new GridBagConstraints();
        gbc.gridx = 2;
        gbc.gridy = 0;
        gbc.anchor = GridBagConstraints.WEST;
        gbc.fill = GridBagConstraints.HORIZONTAL;
        panel6.add(txtAutoOnTopSpan, gbc);
        final JPanel spacer2 = new JPanel();
        gbc = new GridBagConstraints();
        gbc.gridx = 3;
        gbc.gridy = 0;
        gbc.weightx = 1.0;
        gbc.fill = GridBagConstraints.HORIZONTAL;
        panel6.add(spacer2, gbc);
        cbEnableOnTopHotKey = new JCheckBox();
        cbEnableOnTopHotKey.setHorizontalTextPosition(2);
        cbEnableOnTopHotKey.setText("全局唤醒热键");
        cbEnableOnTopHotKey.setToolTipText("监听全局热键[ctrl+shift+alt]按下后,马上前置窗口");
        gbc = new GridBagConstraints();
        gbc.gridx = 0;
        gbc.gridy = 1;
        gbc.anchor = GridBagConstraints.WEST;
        panel6.add(cbEnableOnTopHotKey, gbc);
        final JPanel panel7 = new JPanel();
        panel7.setLayout(new GridBagLayout());
        gbc = new GridBagConstraints();
        gbc.gridx = 0;
        gbc.gridy = 2;
        gbc.weightx = 1.0;
        gbc.weighty = 1.0;
        gbc.fill = GridBagConstraints.BOTH;
        panel3.add(panel7, gbc);
        panel7.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(), "颜色设置", TitledBorder.DEFAULT_JUSTIFICATION, TitledBorder.DEFAULT_POSITION, null, null));
        colorChooser = new ColorChooserPanel();
        gbc = new GridBagConstraints();
        gbc.gridx = 0;
        gbc.gridy = 1;
        gbc.weightx = 1.0;
        gbc.weighty = 1.0;
        gbc.fill = GridBagConstraints.BOTH;
        panel7.add(colorChooser, gbc);
        final JPanel panel8 = new JPanel();
        panel8.setLayout(new GridBagLayout());
        gbc = new GridBagConstraints();
        gbc.gridx = 0;
        gbc.gridy = 0;
        gbc.fill = GridBagConstraints.BOTH;
        panel7.add(panel8, gbc);
        rbFontColor = new JRadioButton();
        rbFontColor.setSelected(true);
        rbFontColor.setText("设置字体色");
        gbc = new GridBagConstraints();
        gbc.gridx = 0;
        gbc.gridy = 0;
        gbc.anchor = GridBagConstraints.WEST;
        panel8.add(rbFontColor, gbc);
        rbBgColor = new JRadioButton();
        rbBgColor.setText("设置背景色");
        gbc = new GridBagConstraints();
        gbc.gridx = 1;
        gbc.gridy = 0;
        gbc.anchor = GridBagConstraints.WEST;
        panel8.add(rbBgColor, gbc);
        ButtonGroup buttonGroup;
        buttonGroup = new ButtonGroup();
        buttonGroup.add(rbBgColor);
        buttonGroup.add(rbFontColor);
    }

    /**
     * @noinspection ALL
     */
    public JComponent $$$getRootComponent$$$() {
        return contentPane;
    }

}
